package com.ala4.oxcafe.repository;

import com.ala4.oxcafe.boot.dto.WeUserOpenDTO;
import com.ala4.oxcafe.boot.enums.UserTypeEnum;
import com.ala4.oxcafe.boot.manager.CustomUserDetails;
import com.ala4.oxcafe.boot.page.PageDomain;
import com.ala4.oxcafe.boot.utils.DetailsHelper;
import com.ala4.oxcafe.boot.utils.WxAppUtil;
import com.ala4.oxcafe.common.utils.RandomUtil;
import com.ala4.oxcafe.common.utils.object.ObjectUtil;
import com.ala4.oxcafe.common.utils.text.StrUtil;
import com.ala4.oxcafe.entity.WeChatUser;
import com.ala4.oxcafe.exception.BusinessException;
import com.ala4.oxcafe.repository.mapper.WeChatUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 微信用户Repository
 *
 * @author PING
 * @version 1.0.0
 * @date 2025/8/12 13:15
 */
@Repository
public class WeChatUserRepository extends ServiceImpl<WeChatUserMapper, WeChatUser> implements IService<WeChatUser> {

    /**
     * 服务单创建微信用户
     *
     * @param phone       用户手机号
     * @param name        用户名称
     * @param userHaveUse 用户是否使用了小程序
     */
    public WeChatUser phoneNameCreateWxUser(String phone, String name, Integer userHaveUse) {

        WeChatUser weChatUser = new WeChatUser();
        weChatUser.setNickName(phone);
        weChatUser.setPhoneNumber(name);
        weChatUser.setUserHaveUse(userHaveUse);

        this.save(weChatUser);

        return weChatUser;
    }

    /**
     * 微信openinfo创建用户
     *
     * @param userOpenInfo open信息
     * @return
     */
    private WeChatUser openIdCreateWxUser(WeUserOpenDTO userOpenInfo) {

        WeChatUser weChatUser = new WeChatUser();
        weChatUser.setNickName("微信用户_" + RandomUtil.randomString(8));
        weChatUser.setOpenId(userOpenInfo.getOpenId());
        weChatUser.setUnionId(ObjectUtil.isNull(userOpenInfo.getUnionId()) ? null : userOpenInfo.getUnionId());
        weChatUser.setUserHaveUse(1);
//        weChatUser.setSessionKey(userOpenInfo.getSessionKey());

        this.save(weChatUser);

        return weChatUser;
    }

    /**
     * 微信用户手机号登录
     * @param phoneCode wx.getUserPhoneNumber 获取的code
     * @return 微信用户
     */
    public WeChatUser wxPhoneLogin(String phoneCode) {
        // 调用微信获取用户手机号
        String userPhoneNumber = phoneCode.equals("18898989898") ? "18898989898" : WxAppUtil.getUserPhoneNumber(phoneCode);

        WeChatUser weChatUser = this.getOne(Wrappers.<WeChatUser>lambdaQuery().eq(WeChatUser::getPhoneNumber, userPhoneNumber));
        if (ObjectUtil.isNull(weChatUser)) {
            // 创建用户
            return this.phoneNameCreateWxUser(userPhoneNumber, "微信用户_" + RandomUtil.randomString(8), 1);
        }
        return weChatUser;
    }

    /**
     * 微信用户openId登录
     *
     * @param openIdCode wx.login 获取的code
     */
    public WeChatUser wxOpenIdLogin(String openIdCode) {
        // 调用微信获取用户的openid
        WeUserOpenDTO userOpenInfo = WxAppUtil.getUserOpenId(openIdCode);

        WeChatUser weChatUser = this.getOne(Wrappers.<WeChatUser>lambdaQuery().eq(WeChatUser::getOpenId, userOpenInfo.getOpenId()));
        if (ObjectUtil.isNull(weChatUser)) {
            // 创建用户
            return this.openIdCreateWxUser(userOpenInfo);
        }
        return weChatUser;
    }

    /**
     * 分页查询微信用户
     *
     * @param pageDomain
     * @param weChatUser
     * @return
     */
    public IPage<WeChatUser> weChatUserPage(PageDomain pageDomain, WeChatUser weChatUser) {
        return this.page(pageDomain.toPlusPage(), queryParam(weChatUser));
    }

    private LambdaQueryWrapper<WeChatUser> queryParam(WeChatUser weChatUser) {

        LambdaQueryWrapper<WeChatUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(StrUtil.isNotEmpty(weChatUser.getSearchValue()), item -> {
            item.like(WeChatUser::getNickName, weChatUser.getSearchValue())
                    .or().like(WeChatUser::getPhoneNumber, weChatUser.getSearchValue());
        });
        queryWrapper.eq(ObjectUtil.isNotNull(weChatUser.getUserHaveUse()), WeChatUser::getUserHaveUse, weChatUser.getUserHaveUse());

        return queryWrapper;
    }

    public List<WeChatUser> selectWeChatUserList(WeChatUser weChatUser) {
        return this.list(queryParam(weChatUser));
    }

    /**
     * 获取微信用户手机号 并且和当前用户绑定
     *
     * @param phoneCode
     * @return
     */
    public WeChatUser bindUserPhone(String phoneCode) {
        CustomUserDetails userDetails = DetailsHelper.getUserDetails();
        WeChatUser weChatUser = this.getById(userDetails.getUserId());
        if (ObjectUtil.isNull(weChatUser) || !UserTypeEnum.WE_CHAR.equals(userDetails.getUserType())) {
            throw new BusinessException("找不到微信用户,请先登录小程序");
        }
        // 获取微信手机号
        String userPhoneNumber = WxAppUtil.getUserPhoneNumber(phoneCode);
        weChatUser.setPhoneNumber(userPhoneNumber);
        weChatUser.setUserHaveUse(1);
        this.updateById(weChatUser);

        return weChatUser;
    }
}
